package com.tiankong.ware.service.impl;

import com.tiankong.ware.entity.Purchase;
import com.tiankong.ware.entity.PurchaseDetail;
import com.tiankong.ware.enums.Status;
import com.tiankong.ware.mapper.PurchaseMapper;
import com.tiankong.ware.service.PurchaseDetailService;
import com.tiankong.ware.service.PurchaseService;
import com.tiankong.ware.service.WareSkuService;
import net.youdi.common.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购信息 服务实现类
 * </p>
 *
 * @author scl
 * @since 2021-03-22
 */
@Service
public class PurchaseServiceImpl extends BaseServiceImpl<PurchaseMapper, Purchase> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public void mergePurchase(Long purchaseId, Set<Long> itemIds) {

        //如果没选择采购单，创建新的采购单进行合并
        if (purchaseId == null){
            Purchase purchase = new Purchase().setStatus(Status.Purchase.CREATED);
            save(purchase);
            purchaseId = purchase.getId();
        }
        purchaseDetailService.update().set("purchase_id",purchaseId)
                .set("status",Status.Purchase.ASSIGNED.getCode()).in("id",itemIds).update();
    }

    @Override
    public void received(Set<Long> ids) {

        //修改采购单状态为已领取（新创建的或已分配的）
        ids = query().in("id", ids).in("status", Arrays.asList(Status.Purchase.CREATED.getCode(), Status.Purchase.ASSIGNED.getCode())).list()
                .stream().map(Purchase::getId).collect(Collectors.toSet());
        update().in("id",ids).set("status",Status.Purchase.RECEIVE.getCode()).update();
        //修改采购项的状态为采购中
        purchaseDetailService.update().in("purchase_id",ids).set("status",Status.Purchase.RECEIVE.getCode()).update();

    }

    @Override
    public void done(Purchase purchase) {
        //2、改变采购项的状态
        List<PurchaseDetail> items = purchase.getItems();
        purchaseDetailService.updateBatchById(items);
        //过滤采购成功的采购项进行入库
        Map<Long, PurchaseDetail> finishedMap = items.stream().filter(item -> Status.Purchase.FINISH == item.getStatus())
                .collect(Collectors.toMap(PurchaseDetail::getId,p->p));

        //1、改变采购单状态
        purchase.setStatus(Status.Purchase.FINISH);
        if (finishedMap.size() != items.size()){
            long count = items.stream().filter(item -> Status.Purchase.HASERROR == item.getStatus()).count();
            if (count > 0){
                purchase.setStatus(Status.Purchase.HASERROR);
            }
        }
        updateById(purchase);
        //3、将成功采购的进行入库
        List<PurchaseDetail> finishedList = purchaseDetailService.query().in("id", finishedMap.keySet()).list();
        wareSkuService.inStock(finishedList);
    }
}
